<!--
 AList File Browser Component
 Author: OpenList Plugin
 Description: Display AList file manager in SiYuan note sidebar
-->
<script lang="ts">
import { onDestroy, onMount } from "svelte";
import { pushMsg } from "./api";
import { inputDialog } from "./libs/dialog";
export let plugin;

    // i18n support - use plugin's built-in i18n data
    let i18nData = plugin.i18n || {};
    
    // i18n translation function
    function t(key: string, params?: Record<string, any>): string {
        const keys = key.split('.');
        let value = i18nData;
        
        for (const k of keys) {
            if (value && typeof value === 'object' && k in value) {
                value = value[k];
            } else {
                console.warn(`i18n key not found: ${key}`);
                return key; // return key as fallback
            }
        }
        
        if (typeof value !== 'string') {
            console.warn(`i18n value is not string: ${key}`);
            return key;
        }
        
        // Replace parameters if provided
        if (params) {
            return value.replace(/\{(\w+)\}/g, (match, paramKey) => {
                return params[paramKey] || match;
            });
        }
        
        return value;
    }

    let isLoading = false;
    let isLoggedIn = false;
    let currentPath = "/";
    let files = [];
    let error = "";
    let token = "";
    let showUpload = false;
    let uploadFiles = [];
    let uploadMode = "stream";
    let addAsTask = false;
    let overwriteExisting = false;
    let tryInstantUpload = true;
    let isUploading = false;
    let uploadProgress = 0;

    // Preview related variables
    let showPreview = false;
    let previewContent = "";
    let previewFile = null;
    let isLoadingPreview = false;

    // Function group related variables
    let showFunctionGroup = false;
    let activeTab = "folder";
    let newFolderName = "";
    let isCreatingFolder = false;
    let selectedFolders = new Set();
    let isDeletingFolders = false;
    let selectedFiles = new Set<string>();
    let isDeletingFiles = false;

    // Upload tab related variables
    let uploadTab = "online"; // "online" or "offline"
    
    // Offline download related variables
    let downloadUrls = "";
    let isOfflineDownloading = false;
    
    // Task list related variables
    let tasks = [];
    let isLoadingTasks = false;
    
    // Move function related variables
    let showMoveDialog = false;
    let moveTargetPath = "/";
    let folderTree = [];
    let expandedFolders = new Set(); // Record expanded folder paths
    let isLoadingFolderTree = false;
    let isMoving = false;
    let allowOverwrite = false;
    let moveItem = null;
    let loadingSubfolders = new Set(); // Record paths of subfolders being loaded // Information of file or folder to move

    onMount(async () => {
        console.log('AList Browser component mounted with i18n data:', Object.keys(i18nData).length, 'keys');
        await initializeAList();
        setupFolderInput();
    });

    onDestroy(() => {
        console.log("AList file browser closed");
    });

    /**
     * Initialize AList connection
     */
    async function initializeAList() {
        const autoLogin = plugin.settingUtils.get("autoLogin");
        if (autoLogin) {
            await loginAndLoadFiles();
        }
    }

    /**
     * Login and load file list
     */
    async function loginAndLoadFiles() {
        const serverUrl = plugin.settingUtils.get("serverUrl");
        const username = plugin.settingUtils.get("username");
        const password = plugin.settingUtils.get("password");
        const rootPath = plugin.settingUtils.get("rootPath") || "/";
        // Get last visited path, use root path if none
        const lastPath = plugin.settingUtils.get("lastPath") || rootPath;

        if (!serverUrl || !username || !password) {
            error = t('errors.configRequired');
            return;
        }

        isLoading = true;
        error = "";

        try {
            const loginResponse = await plugin.loginToAList(serverUrl, username, password);
            token = loginResponse.token;
            // Save token to settings for use elsewhere
            await plugin.settingUtils.setAndSave("token", token);
            isLoggedIn = true;
            currentPath = lastPath;
            await loadFiles(currentPath);
        } catch (err) {
            console.error("Login failed:", err);
            // Detailed error classification and handling
            if (err.message.includes('Failed to fetch') || err.message.includes('NetworkError')) {
                error = t('errors.networkError');
            } else if (err.message.includes('401') || err.message.includes('Unauthorized')) {
                error = t('errors.authError');
            } else if (err.message.includes('403') || err.message.includes('Forbidden')) {
                error = t('errors.forbiddenError');
            } else if (err.message.includes('404') || err.message.includes('Not Found')) {
                error = t('errors.notFoundError');
            } else if (err.message.includes('timeout')) {
                error = t('errors.timeoutError');
            } else {
                error = `❌ ${t('login')} ${t('errors.unknownError')}: ${err.message || t('errors.unknownError')}`;
            }
            isLoggedIn = false;
        } finally {
            isLoading = false;
        }
    }

    /**
     * Load file list for specified path
     * @param {string} path - File path
     * @param {boolean} forceRefresh - Whether to force refresh, not using cache
     */
    async function loadFiles(path, forceRefresh = false) {
        if (!isLoggedIn || !token) {
            error = t('errors.loginRequired');
            return;
        }

        isLoading = true;
        error = "";

        try {
            const serverUrl = plugin.settingUtils.get("serverUrl");
            const response = await fetch(`${serverUrl}/api/fs/list`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token
                },
                body: JSON.stringify({
                    path: path,
                    password: "",
                    page: 1,
                    per_page: 0,
                    refresh: forceRefresh
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            const data = await response.json();
            if (data.code !== 200) {
                throw new Error(data.message || t('errors.failedToGetFileList'));
            }

            files = data.data.content || [];
            currentPath = path;
            // Save current path to settings for restoration on next open
            await plugin.settingUtils.setAndSave("lastPath", path);
        } catch (err) {
            console.error("Load files failed:", err);
            // Detailed error classification and handling
            if (err.message.includes('Failed to fetch') || err.message.includes('NetworkError')) {
                error = t('errors.networkError');
            } else if (err.message.includes('401') || err.message.includes('Unauthorized')) {
                error = t('errors.loginExpired');
                isLoggedIn = false;
                token = "";
            } else if (err.message.includes('403') || err.message.includes('Forbidden')) {
                error = t('errors.accessDenied');
                isLoggedIn = false;
                token = "";
            } else if (err.message.includes('404') || err.message.includes('Not Found')) {
                error = t('errors.pathNotFound');
            } else if (err.message.includes('timeout')) {
                error = t('errors.loadTimeout');
            } else {
                error = `❌ ${t('loading')} ${t('errors.unknownError')}: ${err.message || t('errors.unknownError')}`;
            }
        } finally {
            isLoading = false;
        }
    }

    /**
     * Enter folder
     */
    async function enterFolder(folderName) {
        const newPath = currentPath === "/" ? `/${folderName}` : `${currentPath}/${folderName}`;
        await loadFiles(newPath);
    }

    /**
     * Go back to parent directory
     */
    async function goBack() {
        if (currentPath === "/") return;
        const parentPath = currentPath.substring(0, currentPath.lastIndexOf("/")) || "/";
        await loadFiles(parentPath);
    }

    /**
     * Format file size
     */
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    /**
     * Format date
     */
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    }

    /**
     * Get file icon
     */
    function getFileIcon(file) {
        if (file.is_dir) {
            return "📁";
        }
        const ext = file.name.split('.').pop()?.toLowerCase();
        switch (ext) {
            case 'txt': case 'md': case 'doc': case 'docx':
                return "📄";
            case 'jpg': case 'jpeg': case 'png': case 'gif': case 'bmp':
                return "🖼️";
            case 'mp4': case 'avi': case 'mov': case 'wmv':
                return "🎬";
            case 'mp3': case 'wav': case 'flac': case 'aac':
                return "🎵";
            case 'zip': case 'rar': case '7z': case 'tar':
                return "📦";
            case 'pdf':
                return "📕";
            default:
                return "📄";
        }
    }



    /**
     * Close upload dialog
     */
    function closeUploadDialog() {
        showUpload = false;
        uploadFiles = [];
        isUploading = false;
        uploadProgress = 0;
    }

    /**
     * Handle file selection
     */
    function handleFileSelect(event) {
        const files = Array.from(event.target.files);
        uploadFiles = [...uploadFiles, ...files];
    }

    /**
     * Handle folder selection
     */
    function handleFolderSelect(event) {
        const files = Array.from(event.target.files);
        uploadFiles = [...uploadFiles, ...files];
    }

    /**
     * 设置文件夹输入的属性
     */
    function setupFolderInput() {
        const folderInput = document.getElementById('folder-input');
        if (folderInput) {
            folderInput.setAttribute('webkitdirectory', '');
        }
    }

    /**
     * 移除选中的文件
     */
    function removeFile(index) {
        uploadFiles = uploadFiles.filter((_, i) => i !== index);
    }

    /**
     * 执行文件上传
     */
    async function uploadFilesToAList() {
        if (uploadFiles.length === 0) {
            error = t('errors.selectFiles');
            return;
        }

        isUploading = true;
        error = "";
        uploadProgress = 0;

        try {
            const serverUrl = plugin.settingUtils.get("serverUrl");
            
            for (let i = 0; i < uploadFiles.length; i++) {
                const file = uploadFiles[i];
                const formData = new FormData();
                
                // 构建文件路径
                const filePath = file.webkitRelativePath || file.name;
                const fullPath = currentPath === "/" ? `/${filePath}` : `${currentPath}/${filePath}`;
                
                formData.append('file', file);
                formData.append('path', currentPath);
                formData.append('as_task', addAsTask.toString());
                
                const response = await fetch(`${serverUrl}/api/fs/put`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': token,
                        'File-Path': encodeURIComponent(fullPath),
                        'As-Task': addAsTask.toString(),
                        'Content-Length': file.size.toString()
                    },
                    body: file
                });

                if (!response.ok) {
                    throw new Error(`${t('upload')} failed: ${response.status} ${response.statusText}`);
                }

                const result = await response.json();
                if (result.code !== 200) {
                    throw new Error(result.message || `${t('upload')} failed`);
                }

                uploadProgress = Math.round(((i + 1) / uploadFiles.length) * 100);
            }

            // 上传完成后刷新文件列表（强制刷新以确保新上传的文件显示）
            await loadFiles(currentPath, true);
            
            // 显示成功提示和刷新提醒
            await pushMsg(`Successfully uploaded ${uploadFiles.length} files! Due to AList background transfer characteristics, if files are not displayed immediately, please click the refresh button.`);
            closeUploadDialog();
            
        } catch (err) {
            console.error("Upload failed:", err);
            error = `${t('upload')} failed: ${err.message || t('errors.unknownError')}`;
        } finally {
            isUploading = false;
        }
    }

    /**
     * 下载文件
     */
    async function downloadFile(file) {
        try {
            const serverUrl = plugin.settingUtils.get("serverUrl");
            const filePath = currentPath === "/" ? `/${file.name}` : `${currentPath}/${file.name}`;
            
            // 获取文件的下载链接
            const response = await fetch(`${serverUrl}/api/fs/get`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token
                },
                body: JSON.stringify({
                    path: filePath
                })
            });
            
            if (!response.ok) {
                throw new Error(`Failed to get file info: ${response.status}`);
            }
            
            const result = await response.json();
            if (result.code !== 200) {
                throw new Error(result.message || t('errors.failedToGetFileInfo'));
            }
            
            const fileInfo = result.data;
            const downloadUrl = fileInfo.raw_url || `${serverUrl}/d${filePath}`;
            
            // 创建下载链接并触发下载
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.download = file.name;
            link.target = '_blank';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
        } catch (err) {
            console.error("Download failed:", err);
            error = `${t('download')} failed: ${err.message || t('errors.unknownError')}`;
        }
    }

    /**
     * 在思源笔记光标位置嵌入AList文件链接
     */
    /**
     * 嵌入 AList 文件链接到思源笔记
     */
    async function embedAListLink(file) {
        try {
            const filePath = currentPath === "/" ? `/${file.name}` : `${currentPath}/${file.name}`;
            
            // 使用自定义协议 alist:// 格式
            const alistLink = `alist://${encodeURIComponent(filePath)}`;
            
            // 创建引用块格式，避免与思源笔记查询嵌入块冲突
            // 使用简化的格式，只显示文件名和AList图标
            const blockContent = `> 🅰️ **AList File**: [${file.name}](${alistLink})`;
            
            console.log('Generated AList link:', alistLink);
            console.log('Block content:', blockContent);
            
            // 使用思源笔记API插入自定义块
            if (window.siyuan && window.siyuan.ws) {
                // 获取当前活动的编辑器
                const protyle = document.querySelector('.protyle:not(.fn__none) .protyle-wysiwyg');
                if (protyle) {
                    // 插入自定义块内容
                    document.execCommand('insertText', false, blockContent);
                    await pushMsg(`AList file block embedded: ${file.name}`);
                } else {
                    // 如果没有活动编辑器，则复制到剪贴板
                    await navigator.clipboard.writeText(blockContent);
                    await pushMsg(`File block copied to clipboard: ${file.name}`);
                }
            } else {
                // 备用方案：复制到剪贴板
                await navigator.clipboard.writeText(blockContent);
                await pushMsg(`File block copied to clipboard: ${file.name}`);
            }
            
        } catch (err) {
             console.error("Embed AList link failed:", err);
             error = `${t('embed')} failed: ${err.message || t('errors.unknownError')}`;
         }
    }

    /**
     * 显示文件预览对话框
     */
    async function showFilePreview(file) {
        previewFile = file;
        showPreview = true;
        isLoadingPreview = true;
        previewContent = "";
        
        try {
            const serverUrl = plugin.settingUtils.get("serverUrl");
            const filePath = currentPath === "/" ? `/${file.name}` : `${currentPath}/${file.name}`;
            
            // 首先尝试获取文件的直接下载链接
            const response = await fetch(`${serverUrl}/api/fs/get`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token
                },
                body: JSON.stringify({
                    path: filePath
                })
            });
            
            if (!response.ok) {
                throw new Error(`获取文件信息失败: ${response.status}`);
            }
            
            const result = await response.json();
            if (result.code !== 200) {
                throw new Error(result.message || 'Failed to get file info');
            }
            
            const fileInfo = result.data;
            
            // 根据文件类型生成预览内容
            if (file.name.match(/\.(jpg|jpeg|png|gif|bmp|webp)$/i)) {
                // 图片预览
                const imageUrl = fileInfo.raw_url || `${serverUrl}/d${filePath}`;
                previewContent = `
                    <div class="obj-box hope-stack">
                        <div class="hope-stack">
                            <img class="hope-image" src="${imageUrl}" alt="${file.name}" style="max-width: 100%; height: auto;" />
                        </div>
                    </div>
                `;
            } else if (file.name.match(/\.(mp4|webm|ogg|avi|mov)$/i)) {
                // 视频预览
                const videoUrl = fileInfo.raw_url || `${serverUrl}/d${filePath}`;
                previewContent = `
                    <div class="obj-box hope-stack">
                        <div class="hope-stack">
                            <video controls style="max-width: 100%; height: auto;">
                                <source src="${videoUrl}" type="video/mp4">
                                Your browser does not support video playback.
                            </video>
                        </div>
                    </div>
                `;
            } else if (file.name.match(/\.(mp3|wav|ogg|flac|aac)$/i)) {
                // 音频预览
                const audioUrl = fileInfo.raw_url || `${serverUrl}/d${filePath}`;
                previewContent = `
                    <div class="obj-box hope-stack">
                        <div class="hope-stack">
                            <audio controls style="width: 100%;">
                                <source src="${audioUrl}" type="audio/mpeg">
                                Your browser does not support audio playback.
                            </audio>
                        </div>
                    </div>
                `;
            } else if (file.name.match(/\.(pdf)$/i)) {
                // PDF 文件预览
                const fileUrl = encodeURIComponent(fileInfo.raw_url || `${serverUrl}/d${filePath}`);
                previewContent = `
                    <div class="obj-box hope-stack">
                        <div class="hope-stack">
                            <iframe 
                                src="https://res.oplist.org/pdf.js/web/viewer.html?file=${fileUrl}" 
                                style="width: 100%; height: 600px; border: none;"
                                title="PDF Preview">
                            </iframe>
                        </div>
                    </div>
                `;
            } else if (file.name.match(/\.(doc|docx|xls|xlsx|ppt|pptx)$/i)) {
                // Office 文档预览 - 使用 Microsoft 预览服务
                const fileUrl = encodeURIComponent(fileInfo.raw_url || `${serverUrl}/d${filePath}`);
                previewContent = `
                    <div class="obj-box hope-stack">
                        <div class="hope-stack">
                            <iframe 
                                src="https://view.officeapps.live.com/op/view.aspx?src=${fileUrl}" 
                                style="width: 100%; height: 600px; border: none;"
                                title="Office Document Preview"
                                onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">
                            </iframe>
                            <div style="display: none; text-align: center; padding: 40px; background: #f8f9fa; border-radius: 4px;">
                                <p style="margin-bottom: 16px; color: #6c757d;">Preview service is temporarily unavailable, please try downloading the file to view</p>
                            </div>
                        </div>
                    </div>
                `;
            } else if (file.name.match(/\.(epub)$/i)) {
                // EPUB 电子书预览
                const fileUrl = encodeURIComponent(fileInfo.raw_url || `${serverUrl}/d${filePath}`);
                previewContent = `
                    <div class="obj-box hope-stack">
                        <div class="hope-stack">
                            <iframe 
                                src="https://res.oplist.org/epub.js/viewer.html?url=${fileUrl}" 
                                style="width: 100%; height: 600px; border: none;"
                                title="EPUB Preview">
                            </iframe>
                        </div>
                    </div>
                `;
            } else if (file.name.match(/\.(md)$/i)) {
                // Markdown 文件预览 - 渲染为 HTML
                try {
                    const textUrl = fileInfo.raw_url || `${serverUrl}/d${filePath}`;
                    const textResponse = await fetch(textUrl, {
                        headers: {
                            'Authorization': token
                        }
                    });
                    const markdownContent = await textResponse.text();
                    
                    // 简单的 Markdown 渲染
                    let htmlContent = markdownContent
                        .replace(/### (.*)/g, '<h3>$1</h3>')
                        .replace(/## (.*)/g, '<h2>$1</h2>')
                        .replace(/# (.*)/g, '<h1>$1</h1>')
                        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                        .replace(/\*(.*?)\*/g, '<em>$1</em>')
                        .replace(/`(.*?)`/g, '<code>$1</code>')
                        .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>')
                        .replace(/^- (.*)/gm, '<li>$1</li>')
                        .replace(/((<li>.*<\/li>\s*)+)/g, '<ul>$1</ul>')
                        .replace(/\n\n/g, '</p><p>')
                        .replace(/^(.*)$/gm, function(match) {
                            if (match.startsWith('<h') || match.startsWith('<ul') || match.startsWith('<li') || match.trim() === '') {
                                return match;
                            }
                            return match;
                        });
                    
                    htmlContent = '<p>' + htmlContent + '</p>';
                    htmlContent = htmlContent.replace(/<p><\/p>/g, '').replace(/<p>(<h[1-6]>)/g, '$1').replace(/(<\/h[1-6]>)<\/p>/g, '$1');
                    
                    previewContent = `
                        <div class="obj-box hope-stack">
                            <div class="hope-stack">
                                <div style="max-height: 500px; overflow-y: auto; padding: 20px; background: var(--b3-theme-surface); border-radius: 4px; line-height: 1.6;">
                                    ${htmlContent}
                                </div>
                            </div>
                        </div>
                    `;
                } catch (textErr) {
                    throw new Error(t('errors.unableToLoadMarkdown'));
                }
            } else if (file.name.match(/\.(txt|json|xml|html|css|js|ts|py|java|cpp|c|h)$/i)) {
                // 其他文本文件预览
                try {
                    const textUrl = fileInfo.raw_url || `${serverUrl}/d${filePath}`;
                    const textResponse = await fetch(textUrl, {
                        headers: {
                            'Authorization': token
                        }
                    });
                    const textContent = await textResponse.text();
                    previewContent = `
                        <div class="obj-box hope-stack">
                            <div class="hope-stack">
                                <pre style="white-space: pre-wrap; word-wrap: break-word; max-height: 400px; overflow-y: auto; padding: 16px; background: var(--b3-theme-surface); border-radius: 4px;">${textContent.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</pre>
                            </div>
                        </div>
                    `;
                } catch (textErr) {
                    throw new Error(t('errors.unableToLoadText'));
                }
            } else {
                // 不支持的文件类型
                previewContent = `
                    <div class="obj-box hope-stack">
                        <div class="hope-stack" style="text-align: center; padding: 40px;">
                            <div style="font-size: 48px; margin-bottom: 16px;">📄</div>
                            <h3>${file.name}</h3>
                            <p>This file type is not supported for preview</p>
                            <p>File size: ${formatFileSize(file.size)}</p>
                        </div>
                    </div>
                `;
            }
            
        } catch (err) {
            console.error("Preview failed:", err);
            previewContent = `<div class="preview-error">${t('errors.previewFailed')}: ${err.message}</div>`;
        } finally {
            isLoadingPreview = false;
        }
    }

    /**
     * 关闭预览对话框
     */
    function closePreview() {
        showPreview = false;
        previewContent = "";
        previewFile = null;
        isLoadingPreview = false;
    }

    /**
     * 显示功能组对话框
     */
    function showFunctionGroupDialog() {
        showFunctionGroup = true;
        activeTab = "folder";
        newFolderName = "";
        selectedFolders.clear();
    }

    /**
     * 关闭功能组对话框
     */
    function closeFunctionGroupDialog() {
        showFunctionGroup = false;
        activeTab = "folder";
        newFolderName = "";
        selectedFolders.clear();
    }

    /**
     * 切换功能组标签页
     */
    function switchTab(tab) {
        activeTab = tab;
        // 如果切换到任务标签页，自动加载任务列表
        if (tab === "task") {
            loadUndoneTasks();
        }
    }

    /**
     * 新建文件夹
     */
    async function createFolder() {
        if (!newFolderName.trim()) {
            error = t('errors.enterFolderName');
            return;
        }

        isCreatingFolder = true;
        error = "";

        try {
            const serverUrl = plugin.settingUtils.get("serverUrl");
            const folderPath = currentPath === "/" ? `/${newFolderName}` : `${currentPath}/${newFolderName}`;
            
            const response = await fetch(`${serverUrl}/api/fs/mkdir`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token
                },
                body: JSON.stringify({
                    path: folderPath
                })
            });
            
            if (!response.ok) {
                throw new Error(`Failed to create folder: ${response.status}`);
            }
            
            const result = await response.json();
            if (result.code !== 200) {
                throw new Error(result.message || t('errors.failedToCreateFolder'));
            }
            
            // 刷新文件列表（强制刷新以确保删除的文件不再显示）
            await loadFiles(currentPath, true);
            
            // 显示成功提示
            await pushMsg(t('messages.folderCreatedSuccess', {name: newFolderName}));
            newFolderName = "";
            
        } catch (err) {
            console.error("Create folder failed:", err);
            error = `${t('messages.failedToCreateFolder')}: ${err.message || t('errors.unknownError')}`;
        } finally {
            isCreatingFolder = false;
        }
    }

    /**
     * 切换文件夹选择状态
     */
    function toggleFolderSelection(folderName) {
        if (selectedFolders.has(folderName)) {
            selectedFolders.delete(folderName);
        } else {
            selectedFolders.add(folderName);
        }
        selectedFolders = selectedFolders; // 触发响应式更新
    }

    /**
     * 删除选中的文件夹
     */
    async function deleteSelectedFolders() {
        if (selectedFolders.size === 0) {
            error = t('errors.selectFoldersToDelete');
            return;
        }

        if (!confirm(t('messages.confirmDeleteFolders', {count: selectedFolders.size}))) {
            return;
        }

        isDeletingFolders = true;
        error = "";

        try {
            const serverUrl = plugin.settingUtils.get("serverUrl");
            
            for (const folderName of selectedFolders) {
                
                
                const response = await fetch(`${serverUrl}/api/fs/remove`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': token
                    },
                    body: JSON.stringify({
                        names: [folderName],
                        dir: currentPath
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`${t('messages.failedToDeleteFolders')}: ${response.status}`);
                }
                
                const result = await response.json();
                if (result.code !== 200) {
                    throw new Error(result.message || t('messages.failedToDeleteFolders'));
                }
            }
            
            // 刷新文件列表（强制刷新以确保删除的文件夹不再显示）
            await loadFiles(currentPath, true);
            
            // 显示成功提示
            await pushMsg(t('messages.foldersDeletedSuccess', {count: selectedFolders.size}));
            selectedFolders.clear();
            
        } catch (err) {
            console.error("Delete folders failed:", err);
            error = `${t('messages.failedToDeleteFolders')}: ${err.message || t('errors.unknownError')}`;
        } finally {
            isDeletingFolders = false;
        }
    }

    /**
     * 切换文件选择状态
     */
    function toggleFileSelection(fileName) {
        if (selectedFiles.has(fileName)) {
            selectedFiles.delete(fileName);
        } else {
            selectedFiles.add(fileName);
        }
        selectedFiles = selectedFiles; // 触发响应式更新
    }

    /**
     * 删除选中的文件
     */
    /**
     * 重命名选中的文件
     */
    async function renameSelectedFile() {
        if (selectedFiles.size === 0) {
            error = t('errors.selectFileToRename');
            return;
        }

        if (selectedFiles.size > 1) {
            error = t('errors.renameOnlyOneFile');
            return;
        }

        const fileName = Array.from(selectedFiles)[0];
        
        // 使用inputDialog替换prompt
        
        inputDialog({
            title: "Rename File",
            placeholder: t('errors.newFileName'),
            defaultText: fileName,
            confirm: async (newName) => {
                 const newFileName = newName as string;
                 if (!newFileName || newFileName === fileName) {
                     return;
                 }
                 
                 if (!newFileName.trim()) {
                     error = t('errors.fileNameRequired');
                     return;
                 }

                 isDeletingFiles = true; // 复用删除状态变量
                 error = "";

                 try {
                     const serverUrl = plugin.settingUtils.get("serverUrl");
                     const oldPath = currentPath === "/" ? `/${fileName}` : `${currentPath}/${fileName}`;
                     
                     const response = await fetch(`${serverUrl}/api/fs/rename`, {
                         method: 'POST',
                         headers: {
                             'Content-Type': 'application/json',
                             'Authorization': token
                         },
                         body: JSON.stringify({
                             name: newFileName.trim(),
                             path: oldPath
                         })
                     });
                     
                     if (!response.ok) {
                         throw new Error(`${t('messages.failedToRenameFile')}: ${response.status}`);
                     }
                     
                     const result = await response.json();
                     if (result.code !== 200) {
                         throw new Error(result.message || t('messages.failedToRenameFile'));
                     }
                     
                     // 显示成功提示
                     await pushMsg(t('messages.fileRenamedSuccess', {oldName: fileName, newName: newFileName.trim()}));
                     
                     // 使用新的刷新函数，确保完全重新渲染
                     await refreshFileList();
                    
                } catch (err) {
                    console.error("Rename file failed:", err);
                    error = `${t('messages.failedToRenameFile')}: ${err.message || t('errors.unknownError')}`;
                } finally {
                    isDeletingFiles = false;
                }
            },
            cancel: () => {
                // 用户取消操作
            }
        });
    }

    /**
     * 移动选中的文件或文件夹
     */
    async function moveSelectedItem() {
        if (selectedFiles.size === 0) {
            error = t('errors.selectItemToMove');
            return;
        }

        if (selectedFiles.size > 1) {
            error = t('errors.moveOnlyOneItem');
            return;
        }

        const itemName = Array.from(selectedFiles)[0];
        moveItem = itemName;
        
        // 加载文件夹树
        await loadFolderTree();
        
        // 显示移动对话框
        showMoveDialog = true;
    }

    /**
     * 加载文件夹树（根目录）
     */
    async function loadFolderTree() {
        if (!isLoggedIn || !token) {
            error = t('errors.loginRequired');
            return;
        }

        isLoadingFolderTree = true;
        error = "";
        expandedFolders.clear();
        loadingSubfolders.clear();

        try {
            const serverUrl = plugin.settingUtils.get("serverUrl");
            
            const response = await fetch(`${serverUrl}/api/fs/dirs`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token
                },
                body: JSON.stringify({
                    path: "/",
                    password: ""
                })
            });
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const data = await response.json();
            if (data.code !== 200) {
                throw new Error(data.message || t('errors.failedToGetFolderList'));
            }
            
            // 为每个文件夹添加树形结构所需的属性
            folderTree = (data.data || []).map(folder => ({
                ...folder,
                path: folder.path || `/${folder.name}`,
                children: [],
                isExpanded: false,
                hasChildren: true // 假设所有文件夹都可能有子文件夹
            }));
        } catch (err) {
            console.error("Load folder tree failed:", err);
            error = `${t('messages.failedToLoadFolderTree')}: ${err.message || t('errors.unknownError')}`;
        } finally {
            isLoadingFolderTree = false;
        }
    }

    /**
     * 加载指定路径的子文件夹
     */
    async function loadSubfolders(folderPath) {
        if (!isLoggedIn || !token) {
            return;
        }

        loadingSubfolders.add(folderPath);
        loadingSubfolders = loadingSubfolders; // 触发响应式更新

        try {
            const serverUrl = plugin.settingUtils.get("serverUrl");
            
            const response = await fetch(`${serverUrl}/api/fs/dirs`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token
                },
                body: JSON.stringify({
                    path: folderPath,
                    password: ""
                })
            });
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const data = await response.json();
            if (data.code !== 200) {
                throw new Error(data.message || t('errors.failedToGetSubfolders'));
            }
            
            // 更新文件夹树中对应节点的子文件夹
            updateFolderChildren(folderTree, folderPath, data.data || []);
            folderTree = folderTree; // 触发响应式更新
            
        } catch (err) {
            console.error("Load subfolders failed:", err);
            error = `${t('messages.failedToLoadSubfolders')}: ${err.message || t('errors.unknownError')}`;
        } finally {
            loadingSubfolders.delete(folderPath);
            loadingSubfolders = loadingSubfolders; // 触发响应式更新
        }
    }

    /**
     * 递归更新文件夹树中指定路径的子文件夹
     */
    function updateFolderChildren(tree, targetPath, children) {
        for (let folder of tree) {
            if (folder.path === targetPath) {
                folder.children = children.map(child => ({
                    ...child,
                    path: child.path || `${targetPath}/${child.name}`.replace('//', '/'),
                    children: [],
                    isExpanded: false,
                    hasChildren: true
                }));
                folder.isExpanded = true;
                return true;
            }
            if (folder.children && folder.children.length > 0) {
                if (updateFolderChildren(folder.children, targetPath, children)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 切换文件夹展开/折叠状态
     */
    async function toggleFolder(folder) {
        if (folder.isExpanded) {
            // 折叠文件夹
            folder.isExpanded = false;
            expandedFolders.delete(folder.path);
        } else {
            // 展开文件夹
            if (folder.children.length === 0) {
                // 首次展开，需要加载子文件夹
                await loadSubfolders(folder.path);
            } else {
                // 已有子文件夹数据，直接展开
                folder.isExpanded = true;
                expandedFolders.add(folder.path);
            }
        }
        folderTree = folderTree; // 触发响应式更新
    }

    /**
     * 递归渲染文件夹树
     */
    function renderFolderTree(folderData, level, isLast = false, prefix = '') {
        const items = [];
        const currentPrefix = level === 0 ? '' : prefix + (isLast ? '└── ' : '├── ');
        items.push({ folder: folderData, level, prefix: currentPrefix, isLast });
        if (folderData.isExpanded && folderData.children) {
            const childPrefix = level === 0 ? '' : prefix + (isLast ? '    ' : '│   ');
            for (let i = 0; i < folderData.children.length; i++) {
                const child = folderData.children[i];
                const childIsLast = i === folderData.children.length - 1;
                items.push(...renderFolderTree(child, level + 1, childIsLast, childPrefix));
            }
        }
        return items;
    }

    /**
     * 重新加载文件列表
     * 直接调用 API 重新获取最新的文件列表
     */
    async function refreshFileList() {
        // 清除选中状态
        selectedFiles.clear();
        selectedFiles = selectedFiles; // 触发响应式更新
        
        // 直接调用 API 重新获取文件列表
        await loadFiles(currentPath, true);
    }

    /**
     * 执行移动操作
     */
    async function executeMove() {
        if (!moveItem || !moveTargetPath) {
            error = t('functionGroup.pleaseSelectTargetFolder');
            return;
        }

        isMoving = true;
        error = "";

        try {
            const serverUrl = plugin.settingUtils.get("serverUrl");
            
            // 检查是文件还是文件夹
            const file = files.find(f => f.name === moveItem);
            const isFolder = file && file.is_dir;
            
            const apiEndpoint = isFolder ? '/api/fs/move_dir' : '/api/fs/move';
            
            const requestBody: any = {
                src_dir: currentPath,
                dst_dir: moveTargetPath,
                names: [moveItem]
            };
            
            // 如果允许覆盖，添加overwrite参数
            if (allowOverwrite) {
                requestBody.overwrite = true;
            }
            
            const response = await fetch(`${serverUrl}${apiEndpoint}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token
                },
                body: JSON.stringify(requestBody)
            });
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const result = await response.json();
            
            // 根据API返回的message判断是否成功
            if (result.message === 'success' || result.code === 200) {
                // 移动成功
                await pushMsg(`${isFolder ? 'Folder' : 'File'} moved successfully: ${moveItem} → ${moveTargetPath}`);
                
                // 使用新的刷新函数，确保完全重新渲染
                await refreshFileList();
                
                // 关闭对话框
                closeMoveDialog();
            } else {
                throw new Error(result.message || t('errors.moveOperationFailed'));
            }
            
        } catch (err) {
            console.error("Move item failed:", err);
            error = `Move failed: ${err.message || t('errors.unknownError')}`;
        } finally {
            isMoving = false;
        }
    }

    /**
     * 移动选中的文件夹
     */
    async function moveSelectedFolder() {
        if (selectedFolders.size === 0) {
            error = t('errors.selectFolderToMove');
            return;
        }

        if (selectedFolders.size > 1) {
            error = t('errors.moveOnlyOneFolder');
            return;
        }

        const folderName = Array.from(selectedFolders)[0];
        moveItem = folderName;
        
        // 加载文件夹树
        await loadFolderTree();
        
        // 显示移动对话框
        showMoveDialog = true;
    }

    /**
     * 关闭移动对话框
     */
    function closeMoveDialog() {
        showMoveDialog = false;
        moveTargetPath = "/";
        moveItem = null;
        allowOverwrite = false;
        folderTree = [];
    }

    async function deleteSelectedFiles() {
        if (selectedFiles.size === 0) {
            error = t('errors.selectFilesToDelete');
            return;
        }

        if (!confirm(`Are you sure you want to delete the selected ${selectedFiles.size} files? This operation cannot be undone!`)) {
            return;
        }

        isDeletingFiles = true;
        error = "";

        try {
            const serverUrl = plugin.settingUtils.get("serverUrl");
            
            for (const fileName of selectedFiles) {
                const response = await fetch(`${serverUrl}/api/fs/remove`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': token
                    },
                    body: JSON.stringify({
                        names: [fileName],
                        dir: currentPath
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`Failed to delete file ${fileName}: ${response.status}`);
                }
                
                const result = await response.json();
                if (result.code !== 200) {
                    throw new Error(result.message || `Failed to delete file ${fileName}`);
                }
            }
            
            // 显示成功提示
            await pushMsg(`Successfully deleted ${selectedFiles.size} files!`);
            
            // 使用新的刷新函数，确保完全重新渲染
            await refreshFileList();
            
        } catch (err) {
            console.error("Delete files failed:", err);
            error = `Failed to delete files: ${err.message || t('errors.unknownError')}`;
        } finally {
            isDeletingFiles = false;
        }
    }

    /**
     * 获取未完成任务列表
     */
    async function loadUndoneTasks() {
        if (!isLoggedIn || !token) {
            error = "Please login first";
            return;
        }

        isLoadingTasks = true;
        error = "";

        try {
            const serverUrl = plugin.settingUtils.get("serverUrl");
            
            // 获取未完成的任务
            const undoneResponse = await fetch(`${serverUrl}/api/admin/task/upload/undone`, {
                method: 'GET',
                headers: {
                    'Authorization': token
                }
            });

            if (!undoneResponse.ok) {
                throw new Error(`HTTP ${undoneResponse.status}: ${undoneResponse.statusText}`);
            }

            const undoneData = await undoneResponse.json();
            if (undoneData.code !== 200) {
                throw new Error(undoneData.message || t('errors.failedToGetUndoneTasks'));
            }

            // 获取已完成的离线下载任务（包括失败的）
            const doneResponse = await fetch(`${serverUrl}/api/task/offline_download/done`, {
                method: 'GET',
                headers: {
                    'Authorization': token
                }
            });

            let doneTasks = [];
            if (doneResponse.ok) {
                const doneData = await doneResponse.json();
                if (doneData.code === 200) {
                    // 显示所有已完成的任务（成功：state=2，失败：state=7）
                    doneTasks = (doneData.data || []).filter(task => task.state === 2 || task.state === 7);
                }
            }

            // 合并未完成任务和已完成任务
            tasks = [...(undoneData.data || []), ...doneTasks];
        } catch (err) {
            console.error("Load tasks failed:", err);
            error = `${t('messages.failedToLoadTasks')}: ${err.message || t('errors.unknownError')}`;
        } finally {
            isLoadingTasks = false;
        }
    }

    /**
     * 离线下载文件
     */
    async function startOfflineDownload() {
        if (!downloadUrls.trim()) {
            error = t('errors.enterDownloadLinks');
            return;
        }

        isOfflineDownloading = true;
        error = "";

        try {
            const serverUrl = plugin.settingUtils.get("serverUrl");
            const urls = downloadUrls.split('\n').filter(url => url.trim());
            
            for (const url of urls) {
                const response = await fetch(`${serverUrl}/api/fs/add_offline_download`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': token
                    },
                    body: JSON.stringify({
                        path: currentPath,
                        urls: [url.trim()],
                        tool: "SimpleHttp",
                        delete_policy: "delete_on_upload_succeed"
                    })
                });

                if (!response.ok) {
                throw new Error(`${t('messages.failedToAddOfflineDownload')}: ${response.status} ${response.statusText}`);
            }

                const result = await response.json();
                if (result.code !== 200) {
                    throw new Error(result.message || t('errors.failedToAddOfflineDownload'));
                }
            }

            // 显示成功提示
            await pushMsg(`Successfully added ${urls.length} offline download tasks!`);
            downloadUrls = "";
            
        } catch (err) {
            console.error("Offline download failed:", err);
            error = `${t('errors.offlineDownloadFailed')}: ${err.message || t('errors.unknownError')}`;
        } finally {
            isOfflineDownloading = false;
        }
    }



    /**
     * 格式化任务名称，移除"download "前缀并优化显示
     */
    /**
     * 格式化任务名称显示
     * @param {string} name - 原始任务名称
     * @returns {string} 格式化后的任务名称
     */
    function formatTaskName(name) {
        if (!name) return t('errors.unknownTask');
        
        // 移除"download "前缀
        let cleanName = name.replace(/^download\s+/, '');
        
        // 移除" to ("之后的存储路径部分
        const toIndex = cleanName.indexOf(' to (');
        if (toIndex !== -1) {
            cleanName = cleanName.substring(0, toIndex);
        }
        
        // 尝试从任务名称中提取URL（处理反引号包围的URL）
        const match = cleanName.match(/`(.+?)`/);
        if (match) {
            const url = match[1];
            try {
                const urlObj = new URL(url);
                const domain = urlObj.hostname;
                // 获取URL路径的最后部分作为文件名
                const pathParts = urlObj.pathname.split('/');
                const fileName = pathParts[pathParts.length - 1] || 'index';
                return `${domain}/${fileName}`;
            } catch {
                // 如果不是有效URL，显示原始URL的关键部分
                return url.length > 50 ? `${url.slice(0, 25)}...${url.slice(-20)}` : url;
            }
        }
        
        // 对于其他类型的任务名称，直接显示清理后的名称
        return cleanName.length > 60 ? `${cleanName.slice(0, 30)}...${cleanName.slice(-25)}` : cleanName;
    }

    // 任务选择状态
    let selectedTasks = new Set();

    /**
     * 切换任务选择状态
     */
    function toggleTaskSelection(taskId) {
        if (selectedTasks.has(taskId)) {
            selectedTasks.delete(taskId);
        } else {
            selectedTasks.add(taskId);
        }
        selectedTasks = selectedTasks; // 触发响应式更新
    }

    /**
     * 全选/取消全选任务
     */
    function toggleAllTasks() {
        if (selectedTasks.size === tasks.length) {
            selectedTasks.clear();
        } else {
            selectedTasks = new Set(tasks.map(task => task.id || task.name));
        }
        selectedTasks = selectedTasks; // 触发响应式更新
    }

    /**
     * 清空已成功的离线下载任务
     * 调用API清除所有已完成状态的任务
     */
    async function clearSucceededTasks() {
        if (!token) {
            error = "Please login first";
            return;
        }

        isLoading = true;
        error = "";

        try {
            const serverUrl = plugin.settingUtils.get("serverUrl");
            
            const response = await fetch(`${serverUrl}/api/task/offline_download/clear_succeeded`, {
                method: 'POST',
                headers: {
                    'Authorization': token,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            const result = await response.json();
            if (result.code !== 200) {
                throw new Error(result.message || t('errors.failedToClearSucceededTasks'));
            }

            // 显示成功提示
            await pushMsg('All successful offline download tasks cleared!');
            
            // 刷新任务列表
            await loadUndoneTasks();
            
        } catch (err) {
            console.error("Clear succeeded tasks error:", err);
            error = `${t('messages.failedToClearSucceededTasks')}: ${err.message || t('errors.unknownError')}`;
        } finally {
            isLoading = false;
        }
    }

    /**
     * 重试已选中的离线下载任务
     * 调用API重试指定的任务ID列表
     */
    async function retrySelectedTasks() {
        if (!token) {
            error = "Please login first";
            return;
        }

        // 检查是否有选中的任务
        if (selectedTasks.size === 0) {
            await pushMsg('Please select tasks to retry first!');
            return;
        }

        isLoading = true;
        error = "";

        try {
            const serverUrl = plugin.settingUtils.get("serverUrl");
            const taskIds = Array.from(selectedTasks);
            
            const response = await fetch(`${serverUrl}/api/task/offline_download/retry_some`, {
                method: 'POST',
                headers: {
                    'Authorization': token,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(taskIds)
            });

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            const result = await response.json();
            if (result.code !== 200) {
                throw new Error(result.message || t('errors.failedToRetrySelectedTasks'));
            }

            // 显示成功提示
            await pushMsg(`Retried ${taskIds.length} selected offline download tasks!`);
            
            // 清空选中状态
            selectedTasks.clear();
            selectedTasks = selectedTasks;
            
            // 刷新任务列表
            await loadUndoneTasks();
            
        } catch (err) {
            console.error("Retry selected tasks error:", err);
            error = `${t('messages.failedToRetrySelectedTasks')}: ${err.message || t('errors.unknownError')}`;
        } finally {
            isLoading = false;
        }
    }

    /**
     * 清空已完成的离线下载任务
     * 调用API清除所有已完成状态的任务
     */
    async function clearDoneTasks() {
        if (!token) {
            error = "Please login first";
            return;
        }

        isLoading = true;
        error = "";

        try {
            const serverUrl = plugin.settingUtils.get("serverUrl");
            
            const response = await fetch(`${serverUrl}/api/task/offline_download/clear_done`, {
                method: 'POST',
                headers: {
                    'Authorization': token,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            const result = await response.json();
            if (result.code !== 200) {
                throw new Error(result.message || t('errors.failedToClearDoneTasks'));
            }

            // 显示成功提示
            await pushMsg('All completed offline download tasks cleared!');
            
            // 刷新任务列表
            await loadUndoneTasks();
            
        } catch (err) {
            console.error("Clear done tasks error:", err);
            error = `${t('messages.failedToClearDoneTasks')}: ${err.message || t('errors.unknownError')}`;
        } finally {
            isLoading = false;
        }
    }

    /**
     * 重试失败的离线下载任务
     */
    async function retryFailedTasks() {
        if (!token) {
            error = "Please login first";
            return;
        }

        isLoading = true;
        error = "";

        try {
            const serverUrl = plugin.settingUtils.get("serverUrl");
            
            const response = await fetch(`${serverUrl}/api/task/offline_download/retry_failed`, {
                method: 'POST',
                headers: {
                    'Authorization': token,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            const result = await response.json();
            if (result.code !== 200) {
                throw new Error(result.message || t('errors.failedToRetryFailedTasks'));
            }

            // 显示成功提示
            await pushMsg('All failed offline download tasks retried!');
            
            // 刷新任务列表
            await loadUndoneTasks();
            
        } catch (err) {
            console.error("Retry failed tasks error:", err);
            error = `${t('messages.failedToRetryFailedTasks')}: ${err.message || t('errors.unknownError')}`;
        } finally {
            isLoading = false;
        }
    }


</script>

<div class="alist-browser">
    <!-- 头部工具栏 -->
    <div class="alist-header">
        <div class="alist-path">
            <button class="b3-button b3-button--small" on:click={goBack} disabled={currentPath === "/" || isLoading}>
                ⬅️ {t('back')}
            </button>
            <span class="alist-current-path">{currentPath}</span>
        </div>
        <div class="alist-actions">
            {#if !isLoggedIn}
                <button class="b3-button b3-button--small" on:click={loginAndLoadFiles} disabled={isLoading}>
                    🔑 {t('login')}
                </button>
            {:else}
                <button class="b3-button b3-button--small" on:click={showFunctionGroupDialog} disabled={isLoading}>
                    ⚙️ {t('functions')}
                </button>
                <button class="b3-button b3-button--small" on:click={refreshFileList} disabled={isLoading}>
                    🔄 {t('refresh')}
                </button>
            {/if}
        </div>
    </div>

    <!-- 内容区域 -->
    <div class="alist-content">
        {#if isLoading}
            <div class="alist-loading">
                <div class="loading-spinner"></div>
                <div class="loading-text">
                    <span class="loading-title">{t('loading')}</span>
                    <span class="loading-subtitle">
                        {#if !isLoggedIn}
                            {t('connectingToServer')}
                        {:else}
                            {t('gettingFileList')}
                        {/if}
                    </span>
                </div>
            </div>
        {:else if error}
            <div class="alist-error">
                <div class="error-icon">⚠️</div>
                <div class="error-message">{error}</div>
                <button class="b3-button b3-button--small" on:click={loginAndLoadFiles}>
                    {t('retry')}
                </button>
            </div>
        {:else if !isLoggedIn}
            <div class="alist-welcome">
                <div class="welcome-icon">📁</div>
                <h3>{t('alistFileBrowser')}</h3>
                <p>{t('errors.configRequired')}</p>
                <button class="b3-button" on:click={loginAndLoadFiles}>
                    🔑 {t('loginNow')}
                </button>
            </div>
        {:else if files.length === 0}
            <div class="alist-empty">
                <div class="empty-icon">📂</div>
                <p>{t('directoryEmpty')}</p>
            </div>
        {:else}
            <div class="alist-file-list">
                {#each files as file}
                    <div class="alist-file-item" class:is-directory={file.is_dir}>
                        {#if file.is_dir && selectedFolders.size > 0}
                            <div class="folder-checkbox">
                                <input 
                                    type="checkbox" 
                                    checked={selectedFolders.has(file.name)}
                                    on:change={() => toggleFolderSelection(file.name)}
                                />
                            </div>
                        {/if}
                        <div class="file-icon">{getFileIcon(file)}</div>
                        <div class="file-info">
                            <div class="file-name" 
                                 on:click={() => file.is_dir ? enterFolder(file.name) : null}
                                 class:clickable={file.is_dir}>
                                {file.name}
                            </div>
                            <div class="file-meta">
                                {#if !file.is_dir}
                                    <span class="file-size">{formatFileSize(file.size)}</span>
                                {/if}
                                <span class="file-date">{formatDate(file.modified)}</span>
                            </div>
                        </div>
                        {#if !file.is_dir}
                            <div class="file-actions">
                                <button 
                                    class="b3-button b3-button--small preview-btn" 
                                    on:click={() => showFilePreview(file)}
                                    title="Preview file"
                                >
                                    👁️ {t('preview')}
                                </button>
                                <button 
                                    class="b3-button b3-button--small download-btn"
                                    on:click={() => downloadFile(file)}
                                    title="Download file"
                                    style="margin-left: 4px;"
                                >
                                    📥 {t('download')}
                                </button>
                                <button 
                                    class="b3-button b3-button--small embed-link-btn"
                                    on:click={() => embedAListLink(file)}
                                    title="Embed to note"
                                    style="margin-left: 4px;"
                                >
                                    📝 {t('embedHere')}
                                </button>
                            </div>
                        {/if}
                    </div>
                {/each}
            </div>
        {/if}
    </div>

    <!-- 上传对话框 -->
    {#if showUpload}
        <div class="upload-overlay" on:click={closeUploadDialog}>
            <div class="upload-dialog" on:click|stopPropagation>
                <div class="upload-header">
                    <h3>📤 {t('upload.title', { path: currentPath })}</h3>
                    <button class="close-btn" on:click={closeUploadDialog}>✕</button>
                </div>
                
                <div class="upload-body">
                    <!-- 文件选择区域 -->
                    <div class="upload-drop-zone">
                        <input 
                            type="file" 
                            multiple 
                            id="file-input" 
                            style="display: none;" 
                            on:change={handleFileSelect}
                        />
                        <input 
                            type="file" 
                            multiple 
                            id="folder-input" 
                            style="display: none;" 
                            on:change={handleFolderSelect}
                        />
                        
                        <h4>{t('upload.dragHint')}</h4>
                        
                        <!-- 文件选择按钮 -->
                        <div class="upload-buttons">
                            <button 
                                class="upload-btn folder-btn" 
                                on:click={() => document.getElementById('folder-input').click()}
                                title={t('upload.selectFolder')}
                            >
                                📁
                            </button>
                            <button 
                                class="upload-btn file-btn" 
                                on:click={() => document.getElementById('file-input').click()}
                                title={t('upload.selectFiles')}
                            >
                                📄
                            </button>
                        </div>
                        
                        <!-- 上传配置行 -->
                        <div class="upload-config-row">
                            <!-- 上传模式选择 -->
                            <div class="upload-mode">
                                <label for="upload-mode-select">{t('upload.mode')}:</label>
                                <select id="upload-mode-select" bind:value={uploadMode} class="b3-select">
                                    <option value="stream">{t('upload.streamMode')}</option>
                                    <option value="form">{t('upload.formMode')}</option>
                                </select>
                            </div>
                            
                            <!-- 上传选项 -->
                            <div class="upload-options">
                                <label class="upload-checkbox">
                                    <input type="checkbox" bind:checked={addAsTask} />
                                    <span>{t('upload.addAsTask')}</span>
                                </label>
                                <label class="upload-checkbox">
                                    <input type="checkbox" bind:checked={overwriteExisting} />
                                    <span>{t('upload.overwriteExisting')}</span>
                                </label>
                                <label class="upload-checkbox">
                                    <input type="checkbox" bind:checked={tryInstantUpload} />
                                    <span>{t('upload.tryInstant')}</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 选中的文件列表 -->
                    {#if uploadFiles.length > 0}
                        <div class="selected-files">
                            <h4>{t('upload.selectedFiles', { count: uploadFiles.length })}:</h4>
                            <div class="file-list">
                                {#each uploadFiles as file, index}
                                    <div class="selected-file">
                                        <span class="file-name">{file.webkitRelativePath || file.name}</span>
                                        <span class="file-size">({formatFileSize(file.size)})</span>
                                        <button class="remove-btn" on:click={() => removeFile(index)}>✕</button>
                                    </div>
                                {/each}
                            </div>
                        </div>
                    {/if}
                    
                    <!-- 上传进度 -->
                    {#if isUploading}
                        <div class="upload-progress">
                            <div class="progress-bar">
                                <div class="progress-fill" style="width: {uploadProgress}%"></div>
                            </div>
                            <span class="progress-text">{uploadProgress}%</span>
                        </div>
                    {/if}
                    
                    <!-- 错误信息 -->
                    {#if error}
                        <div class="upload-error">{error}</div>
                    {/if}
                </div>
                
                <div class="upload-footer">
                    <button class="b3-button" on:click={closeUploadDialog} disabled={isUploading}>
                        {t('upload.cancel')}
                    </button>
                    <button 
                        class="b3-button b3-button--primary" 
                        on:click={uploadFilesToAList} 
                        disabled={uploadFiles.length === 0 || isUploading}
                    >
                        {#if isUploading}
                            {t('upload.uploading')}
                        {:else}
                            {t('upload.startUpload')}
                        {/if}
                    </button>
                </div>
            </div>
        </div>
    {/if}

    <!-- 功能组对话框 -->
    {#if showFunctionGroup}
        <div class="function-overlay" on:click={closeFunctionGroupDialog}>
            <div class="function-dialog" on:click|stopPropagation>
                <div class="function-header">
                    <h3>⚙️ {t('functionGroup.title')}</h3>
                    <button class="close-btn" on:click={closeFunctionGroupDialog}>✕</button>
                </div>
                
                <div class="function-tabs">
                    <button 
                        class="tab-btn" 
                        class:active={activeTab === "folder"}
                        on:click={() => switchTab("folder")}
                    >
                        {t('functionGroup.folderManagement')}
                    </button>
                    <button 
                        class="tab-btn" 
                        class:active={activeTab === "file"}
                        on:click={() => switchTab("file")}
                    >
                        {t('functionGroup.fileManagement')}
                    </button>
                    <button 
                        class="tab-btn" 
                        class:active={activeTab === "upload"}
                        on:click={() => switchTab("upload")}
                    >
                        {t('functionGroup.uploadFiles')}
                    </button>
                    <button 
                        class="tab-btn" 
                        class:active={activeTab === "task"}
                        on:click={() => switchTab("task")}
                    >
                        {t('functionGroup.taskList')}
                    </button>
                </div>
                
                <div class="function-body">
                    {#if activeTab === "folder"}
                        <div class="folder-management">
                            <!-- 新建文件夹 -->
                            <div class="function-section">
                                <h4>{t('functionGroup.createNewFolder')}</h4>
                                <div class="input-group">
                                    <input 
                                        type="text" 
                                        bind:value={newFolderName}
                                        placeholder={t('functionGroup.enterFolderName')}
                                        class="b3-text-field"
                                        disabled={isCreatingFolder}
                                        on:keydown={(e) => e.key === 'Enter' && createFolder()}
                                    />
                                    <button 
                                        class="b3-button b3-button--primary"
                                        on:click={createFolder}
                                        disabled={isCreatingFolder || !newFolderName.trim()}
                                    >
                                        {#if isCreatingFolder}
                                            {t('functionGroup.creating')}
                                        {:else}
                                            {t('functionGroup.create')}
                                        {/if}
                                    </button>
                                </div>
                            </div>
                            
                            <!-- 删除文件夹 -->
                            <div class="function-section">
                                <h4>{t('functionGroup.deleteFolder')}</h4>
                                <p class="section-desc">{t('functionGroup.selectFoldersToDelete')}</p>
                                
                                <div class="folder-selection">
                                    {#if files.filter(f => f.is_dir).length === 0}
                                        <p class="no-folders">{t('functionGroup.noFoldersInDirectory')}</p>
                                    {:else}
                                        <div class="folder-list">
                                            {#each files.filter(f => f.is_dir) as folder}
                                                <label class="folder-item">
                                                    <input 
                                                        type="checkbox" 
                                                        checked={selectedFolders.has(folder.name)}
                                                        on:change={() => toggleFolderSelection(folder.name)}
                                                    />
                                                    <span class="folder-name">📁 {folder.name}</span>
                                                </label>
                                            {/each}
                                        </div>
                                        
                                        {#if selectedFolders.size > 0}
                                            <div class="delete-actions">
                                                <p class="selected-count">{t('functionGroup.selectedFolders', {count: selectedFolders.size})}</p>
                                                <div class="folder-action-buttons">
                                                    <button 
                                                        class="b3-button b3-button--danger"
                                                        on:click={deleteSelectedFolders}
                                                        disabled={isDeletingFolders}
                                                        style="margin-right: 8px;"
                                                    >
                                                        {#if isDeletingFolders}
                                                            {t('functionGroup.deleting')}
                                                        {:else}
                                                            {t('functionGroup.deleteSelectedFolders')}
                                                        {/if}
                                                    </button>
                                                    <button 
                                                        class="b3-button"
                                                        on:click={moveSelectedFolder}
                                                        disabled={isDeletingFolders || selectedFolders.size !== 1}
                                                        style="background-color: #FF9800; color: white;"
                                                        title={selectedFolders.size > 1 ? t('functionGroup.moveOperationSingleFolder') : t('functionGroup.moveSelectedFolder')}
                                                    >
                                                        {t('functionGroup.move')}
                                                    </button>
                                                </div>
                                            </div>
                                        {/if}
                                    {/if}
                                </div>
                            </div>
                        </div>
                    {:else if activeTab === "file"}
                        <div class="file-management">
                            <div class="function-section">
                                
                                <div class="file-selection">
                                    {#if files.filter(f => !f.is_dir).length === 0}
                                        <p class="no-files">{t('functionGroup.noFilesInDirectory')}</p>
                                    {:else}
                                        <div class="file-list">
                                            {#each files.filter(f => !f.is_dir) as file}
                                                <label class="file-item">
                                                    <input 
                                                        type="checkbox" 
                                                        checked={selectedFiles.has(file.name)}
                                                        on:change={() => toggleFileSelection(file.name)}
                                                    />
                                                    <span class="file-icon">{getFileIcon(file)}</span>
                                                    <span class="file-name">{file.name}</span>
                                                    <span class="file-size">({formatFileSize(file.size)})</span>
                                                </label>
                                            {/each}
                                        </div>
                                        
                                        {#if selectedFiles.size > 0}
                                            <div class="delete-actions">
                                                <p class="selected-count">{t('functionGroup.selectedFiles', {count: selectedFiles.size})}</p>
                                                <div class="file-action-buttons">
                                                    <button 
                                                        class="b3-button"
                                                        on:click={deleteSelectedFiles}
                                                        disabled={isDeletingFiles}
                                                        style="background-color: #f44336; color: white; margin-right: 8px;"
                                                    >
                                                        {#if isDeletingFiles}
                                                            {t('functionGroup.deleting')}
                                                        {:else}
                                                            {t('functionGroup.deleteSelected')}
                                                        {/if}
                                                    </button>
                                                    <button 
                                                        class="b3-button"
                                                        on:click={renameSelectedFile}
                                                        disabled={isDeletingFiles || selectedFiles.size !== 1}
                                                        style="background-color: #2196F3; color: white; margin-right: 8px;"
                                                        title={selectedFiles.size > 1 ? t('functionGroup.renameOperationSingleFile') : t('functionGroup.renameSelectedFile')}
                                                    >
                                                        {t('functionGroup.rename')}
                                                    </button>
                                                    <button 
                                                        class="b3-button"
                                                        on:click={moveSelectedItem}
                                                        disabled={isDeletingFiles || selectedFiles.size !== 1}
                                                        style="background-color: #FF9800; color: white;"
                                                        title={selectedFiles.size > 1 ? t('functionGroup.moveOperationSingleFile') : t('functionGroup.moveSelectedFile')}
                                                    >
                                                        {t('functionGroup.move')}
                                                    </button>
                                                </div>
                                            </div>
                                        {/if}
                                    {/if}
                                </div>
                            </div>
                        </div>
                    {:else if activeTab === "upload"}
                        <div class="upload-management">
                            <!-- 上传方式标签页 -->
                            <div class="upload-method-tabs">
                                <button 
                                    class="upload-method-tab" 
                                    class:active={uploadTab === "online"}
                                    on:click={() => uploadTab = "online"}
                                >
                                    🌐 {t('functionGroup.onlineUpload')}
                                </button>
                                <button 
                                    class="upload-method-tab" 
                                    class:active={uploadTab === "offline"}
                                    on:click={() => uploadTab = "offline"}
                                >
                                    📥 {t('functionGroup.offlineDownload')}
                                </button>
                            </div>
                            
                            {#if uploadTab === "online"}
                                <!-- 在线上传区域 -->
                                <div class="function-section">
                                    <h4>📤 {t('functionGroup.onlineUploadTo', {path: currentPath})}</h4>
                                <div class="upload-drop-zone">
                                    <input 
                                        type="file" 
                                        multiple 
                                        id="function-file-input" 
                                        style="display: none;" 
                                        on:change={handleFileSelect}
                                    />
                                    <input 
                                        type="file" 
                                        multiple 
                                        id="function-folder-input" 
                                        style="display: none;" 
                                        on:change={handleFolderSelect}
                                    />
                                    
                                    <h5>{t('functionGroup.dragFilesHere')}</h5>
                                    
                                    <!-- 文件选择按钮 -->
                                    <div class="upload-buttons">
                                        <button 
                                            class="upload-btn folder-btn" 
                                            on:click={() => document.getElementById('function-folder-input').click()}
                                            title={t('functionGroup.selectFolder')}
                                        >
                                            📁
                                        </button>
                                        <button 
                                            class="upload-btn file-btn" 
                                            on:click={() => document.getElementById('function-file-input').click()}
                                            title={t('functionGroup.selectFiles')}
                                        >
                                            📄
                                        </button>
                                    </div>
                                    
                                    <!-- 上传配置行 -->
                                    <div class="upload-config-row">
                                        <!-- 上传模式选择 -->
                                        <div class="upload-mode">
                                            <label for="function-upload-mode-select">{t('functionGroup.mode')}:</label>
                                            <select id="function-upload-mode-select" bind:value={uploadMode} class="b3-select">
                                                <option value="stream">{t('functionGroup.stream')}</option>
                                                <option value="form">{t('functionGroup.form')}</option>
                                            </select>
                                        </div>
                                        
                                        <!-- 上传选项 -->
                                        <div class="upload-options">
                                            <label class="upload-checkbox">
                                                <input type="checkbox" bind:checked={addAsTask} />
                                                <span>{t('functionGroup.addAsTask')}</span>
                                            </label>
                                            <label class="upload-checkbox">
                                                <input type="checkbox" bind:checked={overwriteExisting} />
                                                <span>{t('functionGroup.overwriteExistingFiles')}</span>
                                            </label>
                                            <label class="upload-checkbox">
                                                <input type="checkbox" bind:checked={tryInstantUpload} />
                                                <span>{t('functionGroup.tryInstantUpload')}</span>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- 选中的文件列表 -->
                                {#if uploadFiles.length > 0}
                                    <div class="selected-files">
                                        <h5>{t('functionGroup.selectedFilesCount', {count: uploadFiles.length})}:</h5>
                                        <div class="file-list">
                                            {#each uploadFiles as file, index}
                                                <div class="selected-file">
                                                    <span class="file-name">{file.webkitRelativePath || file.name}</span>
                                                    <span class="file-size">({formatFileSize(file.size)})</span>
                                                    <button class="remove-btn" on:click={() => removeFile(index)}>✕</button>
                                                </div>
                                            {/each}
                                        </div>
                                    </div>
                                {/if}
                                
                                <!-- 上传进度 -->
                                {#if isUploading}
                                    <div class="upload-progress">
                                        <div class="progress-bar">
                                            <div class="progress-fill" style="width: {uploadProgress}%"></div>
                                        </div>
                                        <span class="progress-text">{uploadProgress}%</span>
                                    </div>
                                {/if}
                                
                                <!-- 上传按钮 -->
                                <div class="upload-actions">
                                    <button 
                                        class="b3-button b3-button--primary" 
                                        on:click={uploadFilesToAList} 
                                        disabled={uploadFiles.length === 0 || isUploading}
                                    >
                                        {#if isUploading}
                                            {t('functionGroup.uploading')}
                                        {:else}
                                            {t('functionGroup.startUpload')}
                                        {/if}
                                    </button>
                                </div>
                                </div>
                            {:else if uploadTab === "offline"}
                                <!-- 离线下载区域 -->
                                <div class="function-section">
                                    <h4>📥 {t('functionGroup.offlineDownloadTo', {path: currentPath})}</h4>
                                    <p class="section-desc">{t('functionGroup.offlineDownloadDesc')}</p>
                                    
                                    <div class="offline-download-area">
                                        <div class="download-input-group">
                                            <label for="download-urls">{t('functionGroup.downloadLinksLabel')}:</label>
                                            <textarea 
                                                id="download-urls"
                                                bind:value={downloadUrls}
                                                placeholder={t('functionGroup.downloadLinksPlaceholder')}
                                                class="b3-text-field download-textarea"
                                                rows="6"
                                                disabled={isOfflineDownloading}
                                            ></textarea>
                                        </div>
                                        
                                        <div class="download-actions">
                                            <button 
                                                class="b3-button b3-button--primary" 
                                                on:click={startOfflineDownload} 
                                                disabled={!downloadUrls.trim() || isOfflineDownloading}
                                            >
                                                {#if isOfflineDownloading}
                                                    {t('functionGroup.adding')}
                                                {:else}
                                                    📥 {t('functionGroup.startOfflineDownload')}
                                                {/if}
                                            </button>
                                        </div>
                                        
                                        <div class="download-tips">
                                            <h5>💡 {t('functionGroup.usageTips')}:</h5>
                                            <ul>
                                                <li>{t('functionGroup.tip1')}</li>
                                                <li>{t('functionGroup.tip2')}</li>
                                                <li>{t('functionGroup.tip3')}</li>
                                                <li>{t('functionGroup.tip4')}</li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            {/if}
                        </div>
                    {:else if activeTab === "task"}
                        <div class="task-management">
                            <!-- 任务列表 -->
                            <div class="function-section">
                                <div class="task-header">
                                    <div class="task-title">
                                        <h4>📋 {t('functionGroup.taskList')}</h4>
                                        <p class="section-desc">{t('functionGroup.taskListDesc')}</p>
                                    </div>
                                    <div class="task-actions">
                                        <button 
                                            class="b3-button task-retry-selected-btn" 
                                            on:click={retrySelectedTasks}
                                            disabled={isLoadingTasks || isLoading || selectedTasks.size === 0}
                                            title={t('functionGroup.retrySelectedTasksTitle', {count: selectedTasks.size})}
                                            style="background-color: #4CAF50; color: white;"
                                        >
                                            {t('functionGroup.retrySelected')}
                                        </button>
                                        <button 
                                            class="b3-button task-retry-btn" 
                                            on:click={retryFailedTasks}
                                            disabled={isLoadingTasks || isLoading}
                                            title={t('functionGroup.retryFailedTasksTitle')}
                                            style="background-color: #FF9800; color: white;"
                                        >
                                            {t('functionGroup.retryFailed')}
                                        </button>
                                        <button 
                                            class="b3-button task-clear-btn" 
                                            on:click={clearSucceededTasks}
                                            disabled={isLoadingTasks || isLoading}
                                            title="Clear all successful offline download tasks"
                                            style="background-color: #2196F3; color: white;"
                                        >
                                            {t('functionGroup.clearSuccessful')}
                                        </button>
                                        <button 
                                            class="b3-button task-clear-done-btn" 
                                            on:click={clearDoneTasks}
                                            disabled={isLoadingTasks || isLoading}
                                            title="Clear all completed offline download tasks"
                                            style="background-color: #9C27B0; color: white;"
                                        >
                                            {t('functionGroup.clearCompleted')}
                                        </button>
                                        <button 
                                            class="b3-button b3-button--primary task-refresh-btn" 
                                            on:click={loadUndoneTasks}
                                            disabled={isLoadingTasks}
                                        >
                                            {#if isLoadingTasks}
                                                {t('functionGroup.refreshing')}
                                            {:else}
                                                {t('refresh')}
                                            {/if}
                                        </button>
                                    </div>
                                </div>
                                
                                <div class="task-content">
                                    {#if isLoadingTasks}
                                        <div class="task-loading">
                                            <div class="loading-spinner"></div>
                                            <p>{t('functionGroup.loadingTaskList')}</p>
                                        </div>
                                    {:else if tasks.length === 0}
                                        <div class="task-empty">
                                            <div class="empty-icon">✅</div>
                                            <p>{t('functionGroup.noTasks')}</p>
                                        </div>
                                    {:else}
                                        <div class="task-table-container">
                                            <table class="task-table">
                                                <thead>
                                                    <tr>
                                                        <th class="task-checkbox-col">
                                                            <input 
                                                                type="checkbox" 
                                                                checked={selectedTasks.size === tasks.length && tasks.length > 0}
                                                                on:change={toggleAllTasks}
                                                            />
                                                        </th>
                                                        <th class="task-status-col">{t('functionGroup.status')}</th>
                                        <th class="task-creator-col">{t('functionGroup.creator')}</th>
                                        <th class="task-name-col">{t('functionGroup.name')}</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    {#each tasks as task}
                                                        <tr class="task-row" class:selected={selectedTasks.has(task.id || task.name)}>
                                                            <td class="task-checkbox-col">
                                                                <input 
                                                                    type="checkbox" 
                                                                    checked={selectedTasks.has(task.id || task.name)}
                                                                    on:change={() => toggleTaskSelection(task.id || task.name)}
                                                                />
                                                            </td>
                                                            <td class="task-status-col">
                                                <span class="task-status-icon">
                                                    {#if task.state === 2}
                                                        ✅
                                                    {:else if task.state === 7}
                                                        ❌
                                                    {:else}
                                                        🔄
                                                    {/if}
                                                </span>
                                            </td>
                                                            <td class="task-creator-col">
                                                                <span class="task-creator">{task.creator || 'admin'}</span>
                                                            </td>
                                                            <td class="task-name-col">
                                                <span class="task-name-text" title="{task.name || t('errors.unknownTask')}">
                                                    {formatTaskName(task.name)}
                                                </span>
                                            </td>
                                                        </tr>
                                                    {/each}
                                                </tbody>
                                            </table>
                                        </div>
                                    {/if}
                                </div>
                            </div>
                        </div>
                    {/if}
                    
                    <!-- 错误信息 -->
                    {#if error}
                        <div class="function-error">{error}</div>
                    {/if}
                </div>
                
                <div class="function-footer">
                    <button class="b3-button" on:click={closeFunctionGroupDialog}>
                        {t('close')}
                    </button>
                </div>
            </div>
        </div>
    {/if}

    <!-- 预览对话框 -->
    {#if showPreview}
        <div class="preview-overlay" on:click={closePreview}>
            <div class="preview-dialog" on:click|stopPropagation>
                <div class="preview-header">
                    <h3>👁️ {t('preview')}: {previewFile?.name}</h3>
                    <button class="close-btn" on:click={closePreview}>✕</button>
                </div>
                
                <div class="preview-body">
                    {#if isLoadingPreview}
                        <div class="preview-loading">
                            <div class="loading-spinner"></div>
                            <span>{t('functionGroup.loadingPreview')}</span>
                        </div>
                    {:else}
                        <div class="preview-content">
                            {@html previewContent}
                        </div>
                    {/if}
                </div>
                
                <div class="preview-footer">
                    <button class="b3-button" on:click={closePreview}>
                        {t('close')}
                    </button>
                </div>
            </div>
        </div>
    {/if}

    <!-- 移动对话框 -->
    {#if showMoveDialog}
        <div class="preview-overlay" on:click={closeMoveDialog}>
            <div class="preview-dialog" on:click|stopPropagation style="max-width: 600px; max-height: 80vh;">
                <div class="preview-header">
                    <h3>📁 {t('functionGroup.moveFileFolder', {item: moveItem})}</h3>
                    <button class="close-btn" on:click={closeMoveDialog}>✕</button>
                </div>
                
                <div class="preview-body" style="padding: 20px;">
                    {#if isLoadingFolderTree}
                        <div class="preview-loading">
                            <div class="loading-spinner"></div>
                            <span>{t('functionGroup.loadingFolderTree')}</span>
                        </div>
                    {:else}
                        <div class="move-content">
                            <div class="move-section">
                                <h4>{t('functionGroup.selectTargetFolder')}:</h4>
                                <div class="folder-tree">
                                    <!-- 根目录选项 -->
                                    <div class="folder-item root-folder" 
                                         class:selected={moveTargetPath === "/"}
                                         on:click={() => moveTargetPath = "/"}>
                                        <div class="folder-content">
                                            <span class="folder-name">/</span>
                                        </div>
                                    </div>
                                    <!-- 递归渲染文件夹树 -->
                                    {#each folderTree as folder}
                                        {#each renderFolderTree(folder, 0) as {folder: currentFolder, prefix}}
                                            <div class="folder-item" 
                                                 class:selected={moveTargetPath === currentFolder.path}>
                                                <div class="folder-content"
                                                     on:click={() => {
                                                         moveTargetPath = currentFolder.path;
                                                         if (currentFolder.hasChildren) {
                                                             toggleFolder(currentFolder);
                                                         }
                                                     }}>
                                                    <span class="tree-prefix">{prefix}</span>
                                                    {#if currentFolder.hasChildren}
                                                        <span class="folder-toggle" 
                                                              on:click|stopPropagation={() => toggleFolder(currentFolder)}>
                                                            {#if loadingSubfolders.has(currentFolder.path)}
                                                                [⋯]
                                                            {:else}
                                                                {currentFolder.isExpanded ? '[-]' : '[+]'}
                                                            {/if}
                                                        </span>
                                                    {:else}
                                                        <span class="folder-toggle"></span>
                                                    {/if}
                                                    <span class="folder-name">{currentFolder.name}</span>
                                                </div>
                                            </div>
                                        {/each}
                                    {/each}
                                </div>
                            </div>
                            
                            <div class="move-options">
                                <label class="option-item">
                                    <input 
                                        type="checkbox" 
                                        bind:checked={allowOverwrite}
                                    />
                                    <span>{t('functionGroup.allowOverwrite')}</span>
                                </label>
                            </div>
                            
                            {#if error}
                                <div class="move-error">{error}</div>
                            {/if}
                        </div>
                    {/if}
                </div>
                
                <div class="preview-footer">
                    <button class="b3-button" on:click={closeMoveDialog}>
                        {t('cancel')}
                    </button>
                    <button 
                        class="b3-button b3-button--primary" 
                        on:click={executeMove}
                        disabled={isMoving || !moveTargetPath || isLoadingFolderTree}
                    >
                        {#if isMoving}
                            {t('functionGroup.moving')}
                                    {:else}
                                        {t('functionGroup.confirmMove')}
                        {/if}
                    </button>
                </div>
            </div>
        </div>
    {/if}


</div>

<style lang="scss">
    .alist-browser {
        height: 100%;
        display: flex;
        flex-direction: column;
        background: var(--b3-theme-background);
    }

    .alist-header {
        padding: 8px;
        border-bottom: 1px solid var(--b3-theme-surface-lighter);
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: var(--b3-theme-surface);
    }

    .alist-path {
        display: flex;
        align-items: center;
        gap: 8px;
        flex: 1;
    }

    .alist-current-path {
        font-size: 12px;
        color: var(--b3-theme-on-surface);
        background: var(--b3-theme-surface-lighter);
        padding: 2px 6px;
        border-radius: 3px;
        font-family: var(--b3-font-family-code);
    }

    .alist-content {
        flex: 1;
        overflow-y: auto;
        padding: 8px;
    }

    .alist-loading {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 200px;
        gap: 12px;
    }

    .loading-spinner {
        width: 24px;
        height: 24px;
        border: 2px solid var(--b3-theme-surface-lighter);
        border-top: 2px solid var(--b3-theme-primary);
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .alist-error {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 200px;
        gap: 12px;
        text-align: center;
    }

    .error-icon {
        font-size: 32px;
    }

    .error-message {
        color: var(--b3-theme-error);
        font-size: 14px;
    }

    .alist-welcome {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 300px;
        gap: 16px;
        text-align: center;
    }

    .welcome-icon {
        font-size: 48px;
    }

    .alist-welcome h3 {
        margin: 0;
        color: var(--b3-theme-on-surface);
    }

    .alist-welcome p {
        margin: 0;
        color: var(--b3-theme-on-surface-light);
        font-size: 14px;
    }

    .alist-empty {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 200px;
        gap: 12px;
    }

    .empty-icon {
        font-size: 32px;
    }

    .alist-file-list {
        display: flex;
        flex-direction: column;
        gap: 2px;
    }

    .alist-file-item {
        display: flex;
        align-items: center;
        padding: 8px;
        border-radius: 4px;
        transition: background-color 0.2s;

        &:hover {
            background: var(--b3-theme-surface-lighter);
            
            .file-actions {
                opacity: 1;
            }
        }

        &.is-directory {
            .file-name {
                color: var(--b3-theme-primary);
            }
        }
    }

    .file-actions {
        margin-left: auto;
        opacity: 0;
        transition: opacity 0.2s;
        
        .preview-btn {
            font-size: 12px;
            padding: 2px 6px;
        }
    }

    .file-icon {
        font-size: 16px;
        width: 20px;
        text-align: center;
    }

    .file-info {
        flex: 1;
        min-width: 0;
    }

    .file-name {
        font-size: 14px;
        color: var(--b3-theme-on-surface);
        word-break: break-all;
        line-height: 1.3;

        &.clickable {
            cursor: pointer;
            color: var(--b3-theme-primary);

            &:hover {
                text-decoration: underline;
            }
        }
    }

    .file-meta {
        display: flex;
        gap: 8px;
        font-size: 11px;
        color: var(--b3-theme-on-surface-light);
        margin-top: 2px;
    }

    .file-size {
        font-family: var(--b3-font-family-code);
    }

    .file-date {
        font-family: var(--b3-font-family-code);
    }

    /* 上传对话框样式 */
    .upload-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1000;
    }

    .upload-dialog {
        background: var(--b3-theme-background);
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        width: 90%;
        max-width: 600px;
        max-height: 80vh;
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }

    .upload-header {
        padding: 16px 20px;
        border-bottom: 1px solid var(--b3-theme-surface-lighter);
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: var(--b3-theme-surface);
    }

    .upload-header h3 {
        margin: 0;
        font-size: 16px;
        color: var(--b3-theme-on-surface);
    }

    .close-btn {
        background: none;
        border: none;
        font-size: 18px;
        cursor: pointer;
        color: var(--b3-theme-on-surface-light);
        padding: 4px;
        border-radius: 4px;
        transition: background-color 0.2s;

        &:hover {
            background: var(--b3-theme-surface-lighter);
        }
    }

    .upload-body {
        padding: 20px;
        overflow-y: auto;
        flex: 1;
    }

    .upload-drop-zone {
        border: 2px dashed var(--b3-theme-surface-lighter);
        border-radius: 8px;
        padding: 24px;
        text-align: center;
        margin-bottom: 16px;
        transition: border-color 0.2s;

        &:hover {
            border-color: var(--b3-theme-primary);
        }
    }

    .upload-drop-zone h4 {
        margin: 0 0 16px 0;
        color: var(--b3-theme-on-surface);
        font-size: 14px;
    }

    .upload-buttons {
        display: flex;
        gap: 12px;
        justify-content: center;
        margin-bottom: 16px;
    }

    .upload-btn {
        width: 60px;
        height: 60px;
        border: 2px solid var(--b3-theme-surface-lighter);
        border-radius: 8px;
        background: var(--b3-theme-surface);
        cursor: pointer;
        font-size: 24px;
        transition: all 0.2s;
        display: flex;
        align-items: center;
        justify-content: center;

        &:hover {
            border-color: var(--b3-theme-primary);
            background: var(--b3-theme-primary-lighter);
        }
    }

    .upload-config-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 16px;
        flex-wrap: wrap;
        margin-bottom: 16px;
        padding: 12px;
        background: var(--b3-theme-surface);
        border-radius: 6px;
    }

    .upload-mode {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        color: var(--b3-theme-on-surface);
        
        label {
            margin: 0;
            font-weight: 500;
        }
        
        .b3-select {
            min-width: 80px;
        }
    }

    .upload-options {
        display: flex;
        gap: 16px;
        align-items: center;
        flex-wrap: wrap;
    }

    .upload-checkbox {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        color: var(--b3-theme-on-surface);
        cursor: pointer;

        input[type="checkbox"] {
            margin: 0;
        }
    }

    .selected-files {
        margin-top: 16px;
        padding: 16px;
        background: var(--b3-theme-surface);
        border-radius: 6px;
    }

    .selected-files h4 {
        margin: 0 0 12px 0;
        font-size: 14px;
        color: var(--b3-theme-on-surface);
    }

    .file-list {
        max-height: 200px;
        overflow-y: auto;
    }

    .selected-file {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px;
        border-radius: 4px;
        margin-bottom: 4px;
        background: var(--b3-theme-background);
    }

    .selected-file .file-name {
        flex: 1;
        font-size: 13px;
        color: var(--b3-theme-on-surface);
        word-break: break-all;
    }

    .selected-file .file-size {
        font-size: 12px;
        color: var(--b3-theme-on-surface-light);
        font-family: var(--b3-font-family-code);
    }

    .remove-btn {
        background: none;
        border: none;
        color: var(--b3-theme-error);
        cursor: pointer;
        padding: 2px 6px;
        border-radius: 3px;
        font-size: 12px;
        transition: background-color 0.2s;

        &:hover {
            background: var(--b3-theme-error-lighter);
        }
    }

    .upload-progress {
        margin-top: 16px;
        padding: 12px;
        background: var(--b3-theme-surface);
        border-radius: 6px;
    }

    .progress-bar {
        width: 100%;
        height: 8px;
        background: var(--b3-theme-surface-lighter);
        border-radius: 4px;
        overflow: hidden;
        margin-bottom: 8px;
    }

    .progress-fill {
        height: 100%;
        background: var(--b3-theme-primary);
        transition: width 0.3s ease;
    }

    .progress-text {
        font-size: 12px;
        color: var(--b3-theme-on-surface);
        text-align: center;
        display: block;
    }

    .upload-error {
        margin-top: 12px;
        padding: 12px;
        background: var(--b3-theme-error-lighter);
        color: var(--b3-theme-error);
        border-radius: 6px;
        font-size: 14px;
        text-align: center;
    }

    .upload-footer {
        padding: 16px 20px;
        border-top: 1px solid var(--b3-theme-surface-lighter);
        display: flex;
        gap: 12px;
        justify-content: flex-end;
        background: var(--b3-theme-surface);
    }

    /* 功能组对话框样式 */
    .function-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
    }
    
    .function-dialog {
        background: var(--b3-theme-background);
        border-radius: 8px;
        width: 90%;
        max-width: 600px;
        max-height: 80vh;
        overflow: hidden;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        border: 1px solid var(--b3-theme-surface-lighter);
    }
    
    .function-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 20px;
        border-bottom: 1px solid var(--b3-theme-surface-lighter);
        background: var(--b3-theme-surface);
    }
    
    .function-header h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: var(--b3-theme-on-surface);
    }
    
    .function-tabs {
        display: flex;
        border-bottom: 1px solid var(--b3-theme-surface-lighter);
        background: var(--b3-theme-surface);
    }
    
    .tab-btn {
        background: none;
        border: none;
        padding: 12px 20px;
        cursor: pointer;
        color: var(--b3-theme-on-surface-light);
        font-size: 14px;
        border-bottom: 2px solid transparent;
        transition: all 0.2s;
    }
    
    .tab-btn:hover {
        background: var(--b3-theme-surface-lighter);
        color: var(--b3-theme-on-surface);
    }
    
    .tab-btn.active {
        color: var(--b3-theme-primary);
        border-bottom-color: var(--b3-theme-primary);
        background: var(--b3-theme-background);
    }
    
    .function-body {
        padding: 20px;
        max-height: 50vh;
        overflow-y: auto;
    }
    
    .function-section {
        margin-bottom: 24px;
    }
    
    .function-section:last-child {
        margin-bottom: 0;
    }
    
    .function-section h4 {
        margin: 0 0 12px 0;
        font-size: 14px;
        font-weight: 600;
        color: var(--b3-theme-on-surface);
    }
    
    .section-desc {
        margin: 0 0 12px 0;
        font-size: 12px;
        color: var(--b3-theme-on-surface-light);
    }
    
    .input-group {
        display: flex;
        gap: 8px;
        align-items: center;
    }
    
    .input-group input {
        flex: 1;
        min-width: 0;
    }
    
    .folder-list {
        max-height: 200px;
        overflow-y: auto;
        border: 1px solid var(--b3-theme-surface-lighter);
        border-radius: 4px;
        padding: 8px;
        margin-bottom: 12px;
    }
    
    .folder-item {
        display: flex;
        align-items: center;
        padding: 6px 8px;
        cursor: pointer;
        border-radius: 4px;
        transition: background-color 0.2s;
    }
    
    .folder-item:hover {
        background: var(--b3-theme-surface-lighter);
    }
    
    .folder-item input[type="checkbox"] {
        margin-right: 8px;
    }
    
    .folder-name {
        font-size: 13px;
        color: var(--b3-theme-on-surface);
    }
    
    .no-folders {
        text-align: center;
        color: var(--b3-theme-on-surface-light);
        font-size: 13px;
        padding: 20px;
        margin: 0;
    }
    
    .delete-actions {
        padding: 12px;
        background: var(--b3-theme-surface);
        border-radius: 4px;
        border: 1px solid var(--b3-theme-surface-lighter);
    }
    
    .selected-count {
        margin: 0 0 8px 0;
        font-size: 12px;
        color: var(--b3-theme-on-surface-light);
    }
    
    .file-action-buttons {
        display: flex;
        gap: 8px;
        align-items: center;
    }
    
    .file-action-buttons .b3-button {
        flex-shrink: 0;
    }
    
    .function-error {
        background: var(--b3-theme-error-lighter);
        color: var(--b3-theme-error);
        padding: 8px 12px;
        border-radius: 4px;
        font-size: 12px;
        margin-top: 12px;
    }
    
    .function-footer {
        padding: 16px 20px;
        border-top: 1px solid var(--b3-theme-surface-lighter);
        background: var(--b3-theme-surface);
        display: flex;
        justify-content: flex-end;
    }

    /* 上传方式标签页样式 */
    .upload-method-tabs {
        display: flex;
        border-bottom: 1px solid var(--b3-theme-surface-lighter);
        background: var(--b3-theme-surface);
        margin: -20px -20px 20px -20px;
        border-radius: 0;
    }
    
    .upload-method-tab {
        background: none;
        border: none;
        padding: 12px 20px;
        cursor: pointer;
        color: var(--b3-theme-on-surface-light);
        font-size: 14px;
        border-bottom: 2px solid transparent;
        transition: all 0.2s;
        flex: 1;
        text-align: center;
    }
    
    .upload-method-tab:hover {
        background: var(--b3-theme-surface-lighter);
        color: var(--b3-theme-on-surface);
    }
    
    .upload-method-tab.active {
        color: var(--b3-theme-primary);
        border-bottom-color: var(--b3-theme-primary);
        background: var(--b3-theme-background);
        font-weight: 500;
    }

    /* 删除文件功能样式 */
    .file-selection {
        margin-top: 12px;
    }

    .file-list {
        max-height: 200px;
        overflow-y: auto;
        border: 1px solid var(--b3-theme-surface-lighter);
        border-radius: 4px;
        padding: 8px;
        margin-bottom: 12px;
    }

    .file-item {
        display: flex;
        align-items: center;
        padding: 6px 8px;
        cursor: pointer;
        border-radius: 4px;
        transition: background-color 0.2s;
        gap: 8px;
    }

    .file-item:hover {
        background: var(--b3-theme-surface-lighter);
    }

    .file-item input[type="checkbox"] {
        margin: 0;
    }

    .file-item .file-icon {
        font-size: 14px;
    }

    .file-item .file-name {
        flex: 1;
        font-size: 13px;
        color: var(--b3-theme-on-surface);
        word-break: break-all;
    }

    .file-item .file-size {
        font-size: 11px;
        color: var(--b3-theme-on-surface-light);
        font-family: var(--b3-font-family-code);
    }

    .no-files {
        text-align: center;
        color: var(--b3-theme-on-surface-light);
        font-size: 13px;
        padding: 20px;
        margin: 0;
    }

    /* 上传功能在功能组中的样式 */
    .upload-management .upload-drop-zone {
        border: 2px dashed var(--b3-theme-surface-lighter);
        border-radius: 6px;
        padding: 16px;
        text-align: center;
        margin-bottom: 12px;
    }

    .upload-management .upload-drop-zone h5 {
        margin: 0 0 12px 0;
        font-size: 13px;
        color: var(--b3-theme-on-surface);
    }

    .upload-management .upload-buttons {
        display: flex;
        gap: 8px;
        justify-content: center;
        margin-bottom: 12px;
    }

    .upload-management .upload-btn {
        width: 40px;
        height: 40px;
        border: 1px solid var(--b3-theme-surface-lighter);
        border-radius: 6px;
        background: var(--b3-theme-surface);
        cursor: pointer;
        font-size: 16px;
        transition: all 0.2s;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .upload-management .upload-btn:hover {
        border-color: var(--b3-theme-primary);
        background: var(--b3-theme-primary-lighter);
    }

    .upload-management .selected-files {
        margin-top: 12px;
        padding: 12px;
        background: var(--b3-theme-surface);
        border-radius: 4px;
    }

    .upload-management .selected-files h5 {
        margin: 0 0 8px 0;
        font-size: 13px;
        color: var(--b3-theme-on-surface);
    }

    .upload-actions {
        margin-top: 12px;
        text-align: center;
    }

    // 预览对话框样式
    .preview-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1000;
    }

    .preview-dialog {
        background: var(--b3-theme-background);
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        width: 95vw;
        max-width: 1200px;
        max-height: 95vh;
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }

    .preview-header {
        padding: 16px;
        border-bottom: 1px solid var(--b3-theme-surface-lighter);
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: var(--b3-theme-surface);

        h3 {
            margin: 0;
            font-size: 16px;
            color: var(--b3-theme-on-surface);
        }

        .close-btn {
            background: none;
            border: none;
            font-size: 18px;
            cursor: pointer;
            color: var(--b3-theme-on-surface);
            padding: 4px;
            border-radius: 4px;
            transition: background-color 0.2s;

            &:hover {
                background: var(--b3-theme-surface-lighter);
            }
        }
    }

    .preview-body {
        flex: 1;
        padding: 16px;
        overflow: auto;
        min-height: 400px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .preview-loading {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 12px;
        color: var(--b3-theme-on-surface);
    }

    .preview-content {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        
        // 重置AList预览内容的样式以适应思源主题
        :global(.obj-box) {
            background: var(--b3-theme-surface) !important;
            border-radius: 8px;
            padding: 16px;
            margin: 16px;
            width: calc(100% - 32px) !important;
            height: calc(100% - 32px) !important;
            display: flex !important;
            flex-direction: column !important;
            box-sizing: border-box !important;
        }
        
        :global(.hope-stack) {
            width: 100% !important;
            height: 100% !important;
            flex: 1 !important;
        }
        
        // 图片样式 - 保持边距和合适尺寸
        :global(.hope-image) {
            max-width: calc(100% - 32px);
            max-height: calc(100% - 32px);
            height: auto;
            border-radius: 4px;
            object-fit: contain;
            margin: 16px;
        }
        
        // PDF和Office文档样式 - A4纸张比例和足够高度
        :global(iframe) {
            width: calc(100% - 32px) !important;
            height: calc(100vh - 200px) !important;
            min-height: 600px !important;
            margin: 16px !important;
            border: none !important;
            border-radius: 4px !important;
        }
        
        // 视频样式 - 保持边距和播放控件可见
        :global(video) {
            max-width: calc(100% - 32px) !important;
            max-height: calc(100% - 64px) !important;
            height: auto;
            margin: 16px !important;
            border-radius: 4px !important;
        }
        
        // 文本和Markdown内容样式 - A4纸张比例
         :global(.text-content), :global(.markdown-content) {
             max-width: 800px !important;
             width: 100% !important;
             height: calc(100vh - 200px) !important;
             min-height: 600px !important;
             margin: 16px auto !important;
             padding: 20px !important;
             background: var(--b3-theme-background) !important;
             border: 1px solid var(--b3-theme-surface-lighter) !important;
             border-radius: 4px !important;
             overflow-y: auto !important;
             font-family: var(--b3-font-family-code) !important;
             font-size: 14px !important;
             line-height: 1.6 !important;
             white-space: pre-wrap !important;
             word-wrap: break-word !important;
             box-sizing: border-box !important;
         }
         
         // Markdown内容特殊样式
         :global(.markdown-content) {
             font-family: var(--b3-font-family) !important;
         }
         
         :global(.markdown-content h1),
         :global(.markdown-content h2),
         :global(.markdown-content h3),
         :global(.markdown-content h4),
         :global(.markdown-content h5),
         :global(.markdown-content h6) {
             color: var(--b3-theme-on-background) !important;
             margin: 16px 0 8px 0 !important;
         }
         
         :global(.markdown-content p) {
             margin: 8px 0 !important;
             color: var(--b3-theme-on-background) !important;
         }
         
         :global(.markdown-content code) {
             background: var(--b3-theme-surface) !important;
             padding: 2px 4px !important;
             border-radius: 3px !important;
             font-family: var(--b3-font-family-code) !important;
         }
         
         :global(.markdown-content pre) {
             background: var(--b3-theme-surface) !important;
             padding: 12px !important;
             border-radius: 4px !important;
             overflow-x: auto !important;
             margin: 12px 0 !important;
         }

    }

    .preview-footer {
        padding: 16px;
        border-top: 1px solid var(--b3-theme-surface-lighter);
        display: flex;
        justify-content: flex-end;
        gap: 12px;
        background: var(--b3-theme-surface-lighter);
        
        .b3-button {
             min-width: 80px;
             padding: 8px 16px;
             
             &:not(.b3-button--primary) {
                 background: var(--b3-theme-surface);
                 border: 1px solid var(--b3-theme-surface-lighter);
                 color: var(--b3-theme-on-surface);
                 
                 &:hover {
                     background: var(--b3-theme-surface-lighter);
                     color: var(--b3-theme-on-surface);
                 }
             }
         }
    }

    // 离线下载样式
    .offline-download-area {
        padding: 16px;
        background: var(--b3-theme-surface);
        border-radius: 6px;
        margin-top: 12px;
    }

    .download-input-group {
        margin-bottom: 16px;

        label {
            display: block;
            margin-bottom: 8px;
            font-size: 13px;
            color: var(--b3-theme-on-surface);
            font-weight: 500;
        }
    }

    .download-textarea {
        width: 100%;
        min-height: 120px;
        resize: vertical;
        font-family: var(--b3-font-family-code);
        font-size: 12px;
        line-height: 1.4;
    }

    .download-actions {
        margin-bottom: 16px;
        text-align: center;
    }

    .download-tips {
        background: var(--b3-theme-surface-lighter);
        padding: 12px;
        border-radius: 4px;
        border-left: 3px solid var(--b3-theme-primary);

        h5 {
            margin: 0 0 8px 0;
            font-size: 13px;
            color: var(--b3-theme-on-surface);
        }

        ul {
            margin: 0;
            padding-left: 16px;
            font-size: 12px;
            color: var(--b3-theme-on-surface-light);
            line-height: 1.4;

            li {
                margin-bottom: 4px;
            }
        }
    }

    // 任务列表样式
    .task-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16px;
        gap: 16px;
    }

    .task-title {
        flex: 1;
        
        h4 {
            margin: 0 0 4px 0;
        }
        
        .section-desc {
            margin: 0;
        }
    }

    .task-actions {
        display: flex;
        gap: 8px;
        flex-shrink: 0;
        align-self: flex-start;
        margin-top: 2px;
    }

    .task-refresh-btn {
        flex-shrink: 0;
    }

    .task-clear-btn {
        flex-shrink: 0;
    }

    .task-retry-selected-btn {
        flex-shrink: 0;
    }

    .task-retry-btn {
        flex-shrink: 0;
    }

    .task-clear-done-btn {
        flex-shrink: 0;
    }

    .task-loading {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 40px;
        gap: 12px;
        color: var(--b3-theme-on-surface);
    }

    .task-empty {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 40px;
        gap: 12px;
        color: var(--b3-theme-on-surface-light);

        .empty-icon {
            font-size: 32px;
        }
    }

    .task-table {
        width: 100%;
        border-collapse: collapse;
        max-height: 400px;
        overflow-y: auto;
        display: block;
        border: 1px solid var(--b3-theme-surface-lighter);
        border-radius: 6px;
    }

    .task-table thead {
        display: table;
        width: 100%;
        table-layout: fixed;
        background: var(--b3-theme-surface-lighter);
    }

    .task-table tbody {
        display: block;
        max-height: 350px;
        overflow-y: auto;
        width: 100%;
    }

    .task-table tr {
        display: table;
        width: 100%;
        table-layout: fixed;
    }

    .task-table th,
    .task-table td {
        padding: 8px 12px;
        text-align: left;
        border-bottom: 1px solid var(--b3-theme-surface-lighter);
        vertical-align: middle;
    }

    .task-table th {
        font-size: 12px;
        font-weight: 600;
        color: var(--b3-theme-on-surface);
        background: var(--b3-theme-surface-lighter);
        position: sticky;
        top: 0;
        z-index: 1;
    }

    .task-table td {
        font-size: 13px;
        color: var(--b3-theme-on-surface);
    }

    .task-table .task-checkbox-col {
        width: 10%;
        text-align: center;
    }

    .task-table .task-status-col {
        width: 10%;
    }

    .task-table .task-creator-col {
        width: 15%;
    }

    .task-table .task-name-col {
        width: 65%;
        min-width: 200px;
    }

    .task-table tbody tr:hover {
        background: var(--b3-theme-surface-lighter);
    }

    .task-table tbody tr:last-child td {
        border-bottom: none;
    }

    

    .task-status-icon {
        font-size: 16px;
        display: inline-block;
        text-align: center;
    }

    .task-name-text {
        word-break: break-all;
        line-height: 1.3;
    }

    .task-creator {
        font-size: 12px;
        color: var(--b3-theme-on-surface-light);
    }

    // 移动对话框样式
    .move-content {
        display: flex;
        flex-direction: column;
        gap: 20px;
    }

    .move-section {
        h4 {
            margin: 0 0 12px 0;
            font-size: 14px;
            color: var(--b3-theme-on-surface);
            font-weight: 600;
        }
    }

    .folder-tree {
        max-height: 300px;
        overflow-y: auto;
        border: 1px solid var(--b3-theme-surface-lighter);
        border-radius: 6px;
        padding: 12px;
        background: var(--b3-theme-surface);
        width: 100%;
        font-family: var(--b3-font-family-code);
        font-size: 13px;
        line-height: 1.2;
    }

    .folder-item {
        margin: 0;
        border-radius: 0;
        transition: background-color 0.2s;
        line-height: 1.2;
        font-family: var(--b3-font-family-code);
        white-space: nowrap;

        &.selected {
            background: var(--b3-theme-primary-lighter);
            color: var(--b3-theme-primary);
        }

        &.root-folder {
            padding: 4px 0;
            cursor: pointer;
            font-weight: 500;
            border-bottom: 1px solid var(--b3-theme-surface-lighter);
            margin-bottom: 8px;

            &:hover {
                background: var(--b3-theme-surface-lighter);
            }
        }

        &:hover {
            background: var(--b3-theme-surface-lighter);
        }
    }

    .folder-content {
        padding: 2px 0;
        cursor: pointer;
        user-select: none;
        font-family: var(--b3-font-family-code);
        color: var(--b3-theme-on-surface);
    }

    .folder-toggle {
        display: inline;
        font-size: 13px;
        cursor: pointer;
        user-select: none;
        color: var(--b3-theme-on-surface);
        margin-right: 1ch;
    }

    .folder-name {
        display: inline;
        font-size: 13px;
        color: var(--b3-theme-on-surface);
        cursor: pointer;
        user-select: none;
    }

    .tree-prefix {
        color: var(--b3-theme-on-surface-light);
        font-family: var(--b3-font-family-code);
        white-space: pre;
    }

    .move-options {
        padding: 12px;
        background: var(--b3-theme-surface-lighter);
        border-radius: 6px;
        border-left: 3px solid var(--b3-theme-primary);
    }

    .option-item {
        display: flex;
        align-items: center;
        cursor: pointer;
        
        input[type="checkbox"] {
            margin-right: 8px;
            cursor: pointer;
        }
        
        span {
            font-size: 13px;
            color: var(--b3-theme-on-surface);
            user-select: none;
        }
    }

    .move-error {
        padding: 8px 12px;
        background: var(--b3-theme-error-lighter);
        color: var(--b3-theme-error);
        border-radius: 4px;
        font-size: 12px;
        border-left: 3px solid var(--b3-theme-error);
    }
</style>

